
const editor_Options_default = {
    schema: null,//dynamic
    theme: "bootstrap3",
    show_errors: "interaction",
    display_required_only: false,//是否只呈现必需的字段
    no_additional_properties: true,
    required_by_default: true,

    form_name_root: "editor_root",
    disable_array_add: true,
    disable_array_delete: true,
    disable_array_reorder: true,
    disable_collapse: true,
    disable_edit_json: true,
    disable_properties: true,
};


//GUID 
function Guid(g) {
    var arr = new Array(); //存放32位数值的数组

    if (typeof (g) === "string") { //如果构造函数的参数为字符串 
        InitByString(arr, g);
    }
    else {
        InitByOther(arr);
    }
    //返回一个值，该值指示 Guid 的两个实例是否表示同一个值。 
    this.Equals = function (o) {
        if (o && o.IsGuid) {
            return this.ToString() === o.ToString();
        }
        else {
            return false;
        }
    }

    //Guid对象的标记 
    this.IsGuid = function () { }
    //返回 Guid 类的此实例值的 String 表示形式。 
    this.ToString = function (format) {
        if (typeof (format) === "string") {
            if (format === "N" || format === "D" || format === "B" || format === "P") {
                return ToStringWithFormat(arr, format);
            }
            else {
                return ToStringWithFormat(arr, "D");
            }
        }
        else {
            return ToStringWithFormat(arr, "D");
        }
    }
    this.toString = function (format) {
        return this.ToString(format);
    }
    //由字符串加载 
    function InitByString(arr, g) {
        g = g.replace(/\{|\(|\)|\}|-/g, "");
        g = g.toLowerCase();
        if (g.length !== 32 || g.search(/[^0-9,a-f]/i) !== -1) {
            InitByOther(arr);
        }
        else {
            for (var i = 0; i < g.length; i++) {
                arr.push(g[i]);
            }
        }
    }
    //由其他类型加载 
    function InitByOther(arr) {
        var i = 32;
        while (i--) {
            arr.push("0");
        }
    }

    /*

    根据所提供的格式说明符，返回此 Guid 实例值的 String 表示形式。

    N  32 位： xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

    D  由连字符分隔的 32 位数字 xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx

    B  括在大括号中、由连字符分隔的 32 位数字：{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}

    P  括在圆括号中、由连字符分隔的 32 位数字：(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)

    */

    function ToStringWithFormat(arr, format) {
        var str;
        switch (format) {
            case "N":
                return arr.toString().replace(/,/g, "");
            case "D":
                str = arr.slice(0, 8) + "-" + arr.slice(8, 12) + "-" + arr.slice(12, 16) + "-" + arr.slice(16, 20) + "-" + arr.slice(20, 32);
                str = str.replace(/,/g, "");
                return str;
            case "B":
                str = ToStringWithFormat(arr, "D");
                str = "{" + str + "}";
                return str;
            case "P":
                str = ToStringWithFormat(arr, "D");
                str = "(" + str + ")";
                return str;
            default:
                return new Guid();
        }
    }
}
//Guid 类的默认实例，其值保证均为零。 
Guid.Empty = new Guid();
//初始化 Guid 类的一个新实例。 
Guid.NewGuid = function () {
    var g = "";
    var i = 32;
    while (i--) {
        g += Math.floor(Math.random() * 16.0).toString(16);
    }
    return new Guid(g);
}

//格式化字符串
String.prototype.format = function (args) {
    var result = this;
    if (arguments.length > 0) {
        if (arguments.length === 1 && typeof (args) === "object") {
            for (var key in args) {
                if (args[key] !== undefined) {
                    var regexp = new RegExp("({" + key + "})", "g");
                    result = result.replace(regexp, args[key]);
                }
            }
        }
        else {
            for (var i = 0; i < arguments.length; i++) {
                if (arguments[i] !== undefined) {
                    var reg_exp = new RegExp("({[" + i + "]})", "g");
                    result = result.replace(reg_exp, arguments[i]);
                }
            }
        }
    }
    return result;
}

// 对Date的扩展，将 Date 转化为指定格式的String 
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符， 
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字) 
// 例子： 
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423 
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18 
Date.prototype.Format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1,                 //月份 
        "d+": this.getDate(),                    //日 
        "h+": this.getHours(),                   //小时 
        "m+": this.getMinutes(),                 //分 
        "s+": this.getSeconds(),                 //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds()             //毫秒 
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

//弹出对话框
function dlg(title, content, btns/*ok cancel close*/, btnclickcallback) {
    var btnstr = "";
    var withclose = false;
    if (!btns) {
        btns = ["ok"];
    }
    if ($.inArray('ok', btns) >= 0) {
        btnstr += '<button type="button" class="btn btn-primary" data-dismiss="modal" data-btntype="ok">确认</button>'
    }
    if ($.inArray('cancel', btns) >= 0) {
        btnstr += '<button type="button" class="btn btn-default" data-dismiss="modal" data-btntype="cancel">取消</button>';
    }
    if ($.inArray('close', btns) >= 0) {
        withclose = true;
    }
    var gid = Guid.NewGuid().ToString();
    var template = ('<div class="modal fade" data-backdrop="static" id="' + gid + '" tabindex="-1" role="dialog">'
        + '<div class="modal-dialog" role="document">'
        + '<div class="modal-content">'
        + '<div class="modal-header">'
        + '<h4 class="modal-title">{0}</h4>'
        + (withclose ? '<button type="button" class="close" data-dismiss="modal" aria-label="Close" data-btntype="close"><span aria-hidden="true">&times;</span></button>' : '')
        + '</div>'
        + '<div class="modal-body">'
        + '{1}'
        + '</div>'
        + '<div class="modal-footer">'
        + '{2}'
        + '</div>'
        + '</div>'
        + '</div>'
        + '</div>').format(title, content, btnstr);
    var dialog = $(template);

    dialog.find("button[data-btntype]").on("click", function (event) {
        if (btnclickcallback) {
            btnclickcallback($(this).data("btntype"), event);
        }

    });
    dialog.on("hidden.bs.modal", function () {
        dialog.remove();//动态对话框隐藏后移除该动态生成的元素
    });
    dialog.modal("show");
}



//将数据提交到webapi
function apiPost(url, data, success, error) {
    $("body").loading("start");
    var resultData = null;
    $.ajax({
        url: url,
        contentType: "application/json;charset=utf-8",
        type: 'POST',
        async: false,    //是否异步
        data: JSON.stringify(data),
        timeout: 10000,    //超时时间
        dataType: 'json',    //返回的数据格式：json/xml/html/script/jsonp/text
        beforeSend: function (xhr) {

        },
        success: function (data, textStatus, jqXHR) {
            if (data) {
                if (data.status !== 1) {
                    dlg("操作失败", data.message);
                }
                else {
                    resultData = data;
                    if (success) {
                        success(data);
                    }
                    else {
                        dlg("提交成功。", data.message);
                    }
                }
            }
            else {
                dlg("异常", "服务器没有反馈任何数据。");
            }
        },
        error: function (xhr, textStatus) {
            var err = "状态:{status}[{statusText}]，响应:[{responseText}]".format(xhr);
            if (error) {
                error(xhr);
            }
            else {
                dlg(textStatus, err);
            }
        },
        complete: function () {
            $("body").loading("stop");
        }
    });
    return resultData;
}

//从webapi获取数据
function apiGet(url, data, success, error, timeout, cache) {
    var resultData = null;
    var async = true;
    if (!success && !error) {
        async = false;
    }
    if (async) {
        $("body").loading("start");
    }

    $.ajax({
        url: url,
        contentType: "application/x-www-form-urlencoded;charset=utf-8",
        type: 'GET',
        async: async,    //是否异步
        data: data,
        cache: (cache == null) ? true : cache,
        timeout: (!timeout) ? 5000 : timeout,    //超时时间
        dataType: 'json',    //返回的数据格式：json/xml/html/script/jsonp/text
        beforeSend: function (xhr) {

        },
        success: function (result, textStatus, jqXHR) {

            resultData = result;
            if (result) {
                if (result.status !== 1) {
                    if (async) {
                        dlg("操作失败", result.message);
                    }
                }
                else {
                    if (success) {
                        success(result);
                    }
                }
            }
            //else {
            //    dlg("异常", "服务器没有反馈任何数据。");
            //}
        },
        error: function (xhr, textStatus) {

            if (error) {
                error(xhr);
            }
            else {
                if (async) {
                    dlg(xhr.status + "-" + xhr.statusText, xhr.responseText);
                }
                else {
                    throw (xhr);
                }
            }

        },
        complete: function () {
            if (async) {
                $("body").loading("stop");
            }

        }
    });
    return resultData;
}

function Dialog() {

}

//输入对话框
Dialog.Input = function (title, defvalue, submit) {

    var gid = Guid.NewGuid().ToString();
    var html = '<div class="modal fade" id="' + gid + '" data-backdrop="static" tabindex="-1" role="dialog" aria-labelledby="' + gid + 'Label" aria-hidden="true">'
        + '   <div class="modal-dialog" role="document">'
        + '     <div class="modal-content">'
        + '       <div class="modal-header">'
        + '         <h5 class="modal-title" id="' + gid + 'Label">' + title + '</h5>'
        + '         <button type="button" class="close" data-dismiss="modal" aria-label="Close">'
        + '           <span aria-hidden="true">&times;</span>'
        + '         </button>'
        + '       </div>'
        + '       <div class="modal-body">'
        + '         <input id="inp_' + gid + '" type="text" style="width:100%" />'
        + '       </div>'
        + '       <div class="modal-footer">'
        + '         <button type="button" id="btnok' + gid + '" class="btn btn-primary">确定</button>'
        + '         <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>'
        + '       </div>'
        + '     </div>'
        + '   </div>'
        + ' </div>';

    var dialog = $(html);
    dialog.find("#btnok" + gid).on("click", function (event) {
        if (submit) {
            try {
                submit($("#inp_" + gid).val());
                dialog.modal("hide");

            } catch (e) {

            }

        }
    });
    dialog.on("hidden.bs.modal", function () {
        dialog.remove();//动态对话框隐藏后移除该动态生成的元素
    });
    dialog.on("shown.bs.modal", function () {
        $("#inp_" + gid).val(defvalue);
        $("#inp_" + gid).select();
    });
    dialog.modal("show");
}

Dialog.Confirm = function (title, content, onok, oncancel) {
    var gid = Guid.NewGuid().ToString();
    var html = '<div class="modal fade" id="' + gid + '" data-backdrop="static" tabindex="-1" role="dialog" aria-labelledby="' + gid + 'Label" aria-hidden="true">'
        + '   <div class="modal-dialog" role="document">'
        + '     <div class="modal-content">'
        + '       <div class="modal-header">'
        + '         <h5 class="modal-title" id="' + gid + 'Label">' + title + '</h5>'
        + '         <button type="button" class="close" data-dismiss="modal" aria-label="Close">'
        + '           <span aria-hidden="true">&times;</span>'
        + '         </button>'
        + '       </div>'
        + '       <div class="modal-body">'
        + content
        + '       </div>'
        + '       <div class="modal-footer">'
        + '         <button type="button" id="btnok' + gid + '" class="btn btn-primary">确定</button>'
        + '         <button type="button" id="btncancel' + gid + '" class="btn btn-secondary">取消</button>'
        + '       </div>'
        + '     </div>'
        + '   </div>'
        + ' </div>';

    var dialog = $(html);
    dialog.find("#btnok" + gid).on("click", function (event) {
        if (onok) {
            onok();
        }

        dialog.modal("hide");
    });
    dialog.find("#btncancel" + gid).on("click", function (event) {
        if (oncancel) {
            oncancel();
        }
        dialog.modal("hide");
    });
    dialog.on("hidden.bs.modal", function () {
        dialog.remove();//动态对话框隐藏后移除该动态生成的元素
    });
    dialog.on("shown.bs.modal", function () {

    });
    dialog.modal("show");
}